<template>
  <el-dialog
    v-model="dialogVisible"
    :title="isEdit ? '编辑组' : '创建组'"
    width="500"
  >
    <el-form :model="TeamForm" ref="TeamFormRef" label-width="auto">
      <el-form-item
        label="组长"
        props="acc"
        :rules="[
          {
            required: true,
            message: '请选择组长',
            trigger: 'change',
          },
        ]"
      >
        <el-select
          v-model="TeamForm.acc"
          filterable
          remote
          reserve-keyword
          placeholder="按 组长姓名/学号 搜索"
          :remote-method="remoteLeaderMethod"
          :loading="selectLoading"
          clearable
          @change="changeLeader"
          :disabled="isEdit"
        >
          <el-option
            v-for="item in leaderOptions"
            :key="item.id"
            :label="item.name"
            :value="item.acc"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="小组编号">
        <el-input v-model="TeamForm.groupNo" placeholder="请输入小组编号" />
      </el-form-item>
      <el-form-item label="小组名称">
        <el-input v-model="TeamForm.groupName" placeholder="请输入小组名称" />
      </el-form-item>

      <el-form-item label="选择项目">
        <el-select
          v-model="TeamForm.listId"
          filterable
          remote
          reserve-keyword
          placeholder="按 项目名称 搜索"
          :remote-method="remoteProjectMethod"
          :loading="selectLoading"
          clearable
        >
          <el-option
            v-for="item in projectOptions"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="onAppend(TeamFormRef)">
          确认
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { reactive, ref, watch } from "vue";
import api from "@/api";
import type { FormInstance } from "element-plus";
import { ElMessage } from "element-plus";
const emit = defineEmits(["refresh"]);

const dialogVisible = ref<boolean>(false);

const TeamFormRef = ref();
const TeamForm = ref<any>({
  groupNo: "",
  acc: "",
  leader: "",
  groupName: "",
  listId: "",
});

const isEdit = ref(false);

const leaderOptions = ref<any[]>([]);
const projectOptions = ref<any[]>([]);
const selectLoading = ref(false);

watch(dialogVisible, (bool) => {
  if (!bool) {
    TeamForm.value = {
      groupNo: "",
      acc: "",
      leader: "",
      groupName: "",
      listId: "",
    };
    isEdit.value = false;
  }
});
const remoteLeaderMethod = (query: any) => {
  if (query) {
    selectLoading.value = true;
    setTimeout(() => {
      api.user
        .selectStudentByName(query)
        .then((res: any) => {
          leaderOptions.value = res.success ? res.data : [];
          selectLoading.value = false;
        })
        .catch(() => {
          selectLoading.value = false;
        });
    }, 200);
  } else {
    leaderOptions.value = [];
  }
};
const remoteProjectMethod = (query: any) => {
  if (query) {
    selectLoading.value = true;

    setTimeout(() => {
      api.project
        .selectCourseListByName(query)
        .then((res: any) => {
          projectOptions.value = res.success ? res.data : [];
          selectLoading.value = false;
        })
        .catch(() => {
          selectLoading.value = false;
        });
    }, 200);
  } else {
    projectOptions.value = [];
  }
};
function changeLeader(val: string) {
  TeamForm.value.leader = leaderOptions.value.filter(
    (v) => v.acc === val
  )[0].name;
}

function onAppend(formEl: FormInstance | undefined) {
  if (!formEl) return;
  //@ts-ignore
  formEl.validate((valid) => {
    if (valid) {
      if (isEdit.value) {
        api.group.updateTeam(TeamForm.value).then((res: any) => {
          ElMessage({
            message: res.message,
            type: res.success ? "success" : "error",
            grouping: true,
            showClose: true,
          });
          if (res.success) {
            emit("refresh");
            dialogVisible.value = false;
          }
        });
      } else {
        api.group.insertTeam(TeamForm.value).then((res: any) => {
          ElMessage({
            message: res.message,
            type: res.success ? "success" : "error",
            grouping: true,
            showClose: true,
          });
          if (res.success) {
            emit("refresh");
            dialogVisible.value = false;
          }
        });
      }
    }
  });
}

const open = (row: any) => {
  if (row) {
    api.group.selectTeamByID(row.id).then((res: any) => {
      remoteLeaderMethod(res.data.leader);
      remoteProjectMethod(res.data.listName);
      TeamForm.value = {
        id: res.data?.id,
        groupNo: res.data?.groupNo,
        acc: res.data?.acc,
        leader: res.data?.leader,
        groupName: res.data?.groupName,
      };
      if(res.data?.listId) TeamForm.value.listId = Number(res.data?.listId);
    });
    isEdit.value = true;
  }

  dialogVisible.value = true;
};

defineExpose({ open });
</script>
